package com.onlinelearn.chatservice.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatService {
    @Autowired
    private ChatRepository chatRepository;

    @Autowired
    private CourseService courseService;

    @Autowired
    private WebSocketService webSocketService;

    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;

    @Autowired
    private UserPreferenceService userPreferenceService;

    @Autowired
    private OfflineMessageRepository offlineMessageRepository;

    public ChatMessage sendMessage(Long senderId, Long courseId, String content, MessageType type) {
        // 验证发送者权限
        validateSender(senderId, courseId);

        // 敏感词过滤
        String filteredContent = sensitiveWordFilter.filter(content);

        ChatMessage message = new ChatMessage();
        message.setSenderId(senderId);
        message.setCourseId(courseId);
        message.setContent(filteredContent);
        message.setType(type);
        message.setTimestamp(LocalDateTime.now());
        message.setStatus(ChatMessageStatus.SENT);

        // 保存消息
        ChatMessage savedMessage = chatRepository.save(message);

        // WebSocket实时推送
        webSocketService.sendMessageToCourse(courseId, savedMessage);

        // 离线消息处理
        handleOfflineMessages(courseId, savedMessage);

        return savedMessage;
    }

    private void validateSender(Long senderId, Long courseId) {
        if (!courseService.isValidChatParticipant(senderId, courseId)) {
            throw new UnauthorizedChatAccessException("无权发送消息");
        }
    }

    private void handleOfflineMessages(Long courseId, ChatMessage message) {
        List<Long> offlineParticipants = courseService.getOfflineParticipants(courseId);
        offlineParticipants.forEach(participantId -> {
            // 存储离线消息
            offlineMessageRepository.save(
                new OfflineMessage(participantId, message)
            );
        });
    }

    public List<ChatMessage> getCourseMessages(Long courseId, LocalDateTime startTime) {
        return chatRepository.findByCourseIdAndTimestampAfter(courseId, startTime);
    }

    public List<OfflineMessage> getOfflineMessages(Long userId) {
        return offlineMessageRepository.findByUserId(userId);
    }
}

@Data
class OfflineMessage {
    private Long userId;
    private ChatMessage message;
    private LocalDateTime receivedTime;
}

enum ChatMessageStatus {
    SENT,       // 已发送
    DELIVERED,  // 已送达
    READ,       // 已读
    PINNED      // 置顶
}

enum MessageType {
    TEXT,
    IMAGE,
    CODE,
    FILE
} 